<?php

namespace App\Http\Controllers\Admin\Shop;

use App\Http\Controllers\Controller;
use App\Models\Shop\Customer;
use GatewayClient\Gateway;
use Illuminate\Http\Request;

class CustomerController extends Controller
{
    public function __construct()
    {
        view()->share([
            '_shop' => 'am-in',
            '_customer' => 'am-active',
        ]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //模糊搜索
        $where = function ($query) use ($request) {
            //按会员名搜索
            if ($request->has('name') and $request->name != '') {
                $search = "%" . $request->name . "%";
                $query->where('nickname', 'like', $search);
            }
            //微信openid搜索
            if ($request->has('oopenid') and $request->openid != '') {
                $search = "%" . $request->openid . "%";
                $query->where('openid', 'like', $search);
            }
            //按性别搜索
            if ($request->has('sex') and $request->sex != '-1') {
                $query->where('sex', $request->sex);
            }
            //按时间搜索
            if ($request->has('created_at') and $request->created_at != '') {
                $time = explode(" ~ ", $request->input('created_at'));
                foreach ($time as $k => $v) {
                    $time["$k"] = $k == 0 ? $v . " 00:00:00" : $v . " 23:59:59";
                }
                $query->whereBetween('created_at', $time);
            }

        };

        $customers = Customer::where($where)->orderBy('id')->paginate(config('admin.page_size'));
        return view('admin.shop.customer.index', compact('customers'));
    }

    /**
     * 改变属性
     */
    public function change_attr(Request $request)
    {
        Gateway::$registerAddress = '127.0.0.1:1238';

        $customer = Customer::find($request->id);
        $attr = $request->attr;
        $customer->$attr = !$customer->$attr;
        $customer->save();

        $data = [
            ['value' => Customer::where('sex', 1)->count(), 'name' => '男'],
            ['value' => Customer::where('sex', 0)->count(), 'name' => '女']
        ];
        Gateway:: sendToGroup('sex', json_encode($data));
    }

}
